<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/10
 * Time: 17:15
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;

class EmployeeModel extends Model
{
    const TABLE = 'employee';

    const DUTY = 1;//在岗
    const PENDING = 2;//待岗
    const LEAVE = 3;//请假
    const RESIGN = 4;//离职
    /**
     * @param array $param
     * @param bool $exports
     * @return mixed
     */
    public function lists(array $param,$exports = false)
    {
        $result = DB::table(self::TABLE)
        ->leftJoin('profession as p', 'p.id', '=', self::TABLE . '.professionId')
        ->leftJoin('project', 'project.id', '=', self::TABLE . '.projectId')
        ->leftJoin('group', 'group.id', '=', self::TABLE . '.groupId')
        ->where(function ($query) use ($param) {
            if (isset($param['isFinish']) && $param['isFinish'] != '') {
                $query->where('isFinish', $param['isFinish']);
            }
            if (isset($param['isManager'])) {
                $query->where('p.isManager', $param['isManager']);
            }
            if (!empty($param['projectId']) && $param['projectId'] != 1) {
                $query->where(self::TABLE.'.projectId', $param['projectId']);
            }
            if (!empty($param['professionId'])) {
                $query->where(self::TABLE.'.professionId', $param['professionId']);
            }
            if (!empty($param['status'])) {
                $query->where(self::TABLE . '.status', $param['status']);
            }
            if (isset($param['search']) && !is_null($param['search'])) {
                $query->where(function ($query1) use ($param) {
                    $query1->where(self::TABLE . '.name', 'like', '%' . $param['search'] . '%')->orWhere('jobNumber', 'like', '%' . $param['search'] . '%');
                });
            }
            if (isset($param['startTime']) && isset($param['endTime'])) {
                $query->whereBetween('entryTime', [$param['startTime'], $param['endTime']]);
            }
        });
        if(!$exports){
            $limit = config('yucheng.limit');
            $start = 0;
            if (!empty($param['length'])) {
                $limit = $param['length'];
            }
            if (!empty($param['page'])) {
                $start = ($param['page']-1)*$limit;
            }
            $result = $result->offset($start)->limit($limit);
        }
        $result = $result->select(self::TABLE . '.*', 'p.name as professionName','p.isManager', 'project.name as projectName','group.name as groupName')
            ->orderBy('jobNumber')
            ->get()->toArray();
        return $result;
    }

    /**
     * @param array $param
     * @return mixed
     */
    public function countLists(array $param)
    {
        return DB::table(self::TABLE)
            ->leftJoin('profession as p', 'p.id', '=', self::TABLE . '.professionId')
            ->leftJoin('project', 'project.id', '=', self::TABLE . '.projectId')
            ->leftJoin('group', 'group.id', '=', self::TABLE . '.groupId')
            ->where(function ($query) use ($param) {
                if (!empty($param['isFinish'])) {
                    $query->where('isFinish', $param['isFinish']);
                }
                if (isset($param['isManager'])) {
                    $query->where('p.isManager', $param['isManager']);
                }
                if (!empty($param['projectId']) && $param['projectId'] != 1) {
                    $query->where(self::TABLE.'.projectId', $param['projectId']);
                }
                if (!empty($param['professionId'])) {
                    $query->where(self::TABLE.'.professionId', $param['professionId']);
                }
                if (isset($param['status']) && !is_null($param['status'])) {
                    $query->where(self::TABLE . '.status', $param['status']);
                }
                if (isset($param['search']) && !is_null($param['search'])) {
                    $query->where(function ($query1) use ($param) {
                        $query1->where(self::TABLE . '.name', 'like', '%' . $param['search'] . '%')->orWhere('jobNumber', 'like', '%' . $param['search'] . '%');
                    });
                }
                if (isset($param['startTime']) && isset($param['endTime'])) {
                    $query->whereBetween('entryTime', [$param['startTime'], $param['endTime']]);
                }
            })
            ->count();
    }

    /**
     * 判断工人身份证号在时间段内是否重复
     * @param $key
     * @param $value
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function checkRepeat($key,$value, $startTime, $endTime)
    {
        return DB::table(self::TABLE)->where($key,$value)->whereBetween('entryTime', [$startTime, $endTime])->count();
    }

    /**
     * @param array $param
     * @return mixed
     */
    public function insert(array $param)
    {
        $param['entryTime'] = date('Y-m-d H:i:s');
        return DB::table(self::TABLE)->insertGetId($param);
    }

    /**
     * @param $data
     * @return array
     */
    public function info($data)
    {
        $result = DB::table(self::TABLE)
            ->leftJoin('profession as pr', 'pr.id', '=', self::TABLE . '.professionId')
            ->leftJoin('project as p', 'p.id', '=', self::TABLE . '.projectId')
            ->where(function ($query) use ($data){
                if (isset($data['id'])){
                    $query->where(self::TABLE . '.id', $data['id']);
                }
                if (isset($data['technicalGroupId'])){
                    $query->where(self::TABLE . '.technicalGroupId', $data['technicalGroupId']);
                }
            })
            ->select([self::TABLE . '.*', 'pr.name as professionName', 'p.name as projectName'])
            ->first();
        return empty($result) ? [] : get_object_vars($result);
    }

    /**
     * @param $id
     * @param string $startTime
     * @param string $endTime
     * @return array|mixed
     * @throws \Exception
     */
    public function wages($id,$startTime= '',$endTime = '')
    {
        $findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
        if (empty($findYear)) {
            $findYear['startTime'] = date('Y-01-01 00:00:00');
            $findYear['endTime'] = date('Y-12-31 23:59:59');
        }

        $startTime = $startTime==''?$findYear['startTime']:$startTime.' 00:00:00';
        $endTime = $endTime==''?$findYear['endTime']:$endTime.' 23:59:59';

        $condition = [
            'employeeId'=>$id,
            'startTime'=>$startTime,
            'endTime'=>$endTime,
        ];
        $workmanAccounts = (new WorkmanAccountsModel())->getAccountsList($condition);
        $handymanAccounts = (new HandymanAccountsModel())->getAccountsList($condition);
        $attendance = (new AttendanceModel())->getLists($condition);
        $loan = (new LoanModel())->getAccountsList($condition);

        $condition['type'] = LivingModel::RECHARGE;
        $livingRecharge = (new LivingModel())->getAccountsList($condition);
        $condition['type'] = LivingModel::REFUND;
        $livingRefund = (new LivingModel())->getAccountsList($condition);
        unset($condition['employeeId']);
        $condition['sourceEmployeeId'] = $id;
        $condition['type'] = WarehouseLogModel::CONSUME;
        //材料费
        $materialAccounts = (new WarehouseLogModel())->getLogs($condition);

        $wageList = $this->datePeriod($startTime, $endTime, '1 month', 'Y-m');
        $endTime = (new \DateTime($endTime))->format('Y-m');
        end($wageList);
        if (key($wageList) != $endTime) {
            $wageList[$endTime] = '';
        }
        foreach ($wageList as $key => $w) {
            $wageList[$key] = [
                'livingRecharge' => 0,
                'livingRefund' => 0,
                'loan' => 0,
                'materialOrder' => 0,
                'attendance' => 0,
                'workmanAccounts' => 0,
                'handymanAccounts' => 0,
            ];
        }

        $wageList = $this->wageList($wageList, $livingRecharge, 'livingRecharge', 'livingTime');
        $wageList = $this->wageList($wageList, $livingRefund, 'livingRefund', 'livingTime');
        $wageList = $this->wageList($wageList, $loan, 'loan', 'loanTime');
        $wageList = $this->wageList($wageList, $materialAccounts, 'materialOrder', 'time','price');
        $wageList = $this->wageList($wageList, $attendance, 'attendance', 'day', 'length');
        $wageList = $this->wageList($wageList, $workmanAccounts, 'workmanAccounts', 'separateTime');
        $wageList = $this->wageList($wageList, $handymanAccounts, 'handymanAccounts', 'separateTime');

        return $wageList;
    }

    /**
     * 把列表按月分组
     * @param $wageList
     * @param $itemList
     * @param $item
     * @param $timeColumn
     * @param string $calcColumn
     * @return mixed
     * @throws \Exception
     */
    public function wageList($wageList, $itemList, $item, $timeColumn, $calcColumn = 'account')
    {
        foreach ($itemList as $i) {
            $month = (new \DateTime($i->$timeColumn))->format('Y-m');
            if (!isset($wageList[$month][$item])) {
                $wageList[$month][$item] = 0;
            }
            $wageList[$month][$item] += $i->$calcColumn;
        }
        return $wageList;
    }

    /**
     * @param array $where
     * @param array $data
     * @return mixed
     */
    public function update(array $where, array $data)
    {
        return DB::table(self::TABLE)->where($where)->update($data);
    }

    /**
     * @param array $ids
     * @param array $data
     * @return mixed
     */
    public function batchUpdate(array $ids, array $data)
    {
        return DB::table(self::TABLE)->whereIn('id',$ids)->update($data);
    }

    /**
     * @param array $data
     * @return mixed
     * @throws \Exception
     */
    public function attendanceList(array $data)
    {
        //获取考勤人员的列表
        $lists = $this->attendanceEmployee($data);
//        if (count($lists) == 0) {
//            return $lists;
//        }

        //获取月考勤，不传月份则默认为当前月份
        if (empty($data['startTime']) && empty($data['endTime'])){
            $startTime = (new \DateTime($data['month']))->format('Y-m-01');
            $endTime = (new \DateTime($data['month']))->format('Y-m-t');
        }else{
            $startTime = $data['startTime'];
            $endTime = $data['endTime'];
        }

        $attendanceModel = new AttendanceModel();
        foreach ($lists as $key => $l) {
            $dayList = $this->datePeriod($startTime, $endTime, '1 day', 'j','attendance');
            $attendances = $attendanceModel->getLists(['employeeId'=>$l->id, 'startTime'=>$startTime, 'endTime'=>$endTime]);
            //审批用的状态值
            if(empty($attendances)){
                $status = 3;
                unset($lists[$key]);
                continue;
            }else{
                $status = 2;
            }

            foreach ($attendances as $a) {
                $d = (new \DateTime($a->day))->format('j');
                $dayList[$d]['long'] = empty($a->length)?'':$a->length;
                $dayList[$d]['day'] = empty($a->day)?'':$a->day;
                $dayList[$d]['projectName'] = empty($a->projectName)?'':$a->projectName;
                $dayList[$d]['projectId'] = empty($a->projectId)?'':$a->projectId;
                $dayList[$d]['isCurrent'] = $a->isCurrent;
                $dayList[$d]['id'] = $a->id;
                //审批用的状态值
                $status = $a->status;
            }
            $lists[$key]->attendance = $dayList;
            //审批用的状态值
            $lists[$key]->attendanceStatus = $status;
        }

        return array_values($lists);
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function attendanceEmployee(array $data)
    {
        $findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
        if (empty($findYear)) {
            $findYear['startTime'] = date('Y-01-01 00:00:00');
            $findYear['endTime'] = date('Y-12-31 23:59:59');
        }
        $result = DB::table(self::TABLE)
            ->leftJoin('profession as p', 'p.id', '=', self::TABLE . '.professionId')
            ->leftJoin('project', 'project.id', '=', self::TABLE . '.projectId')
            ->where(function ($query) use ($data,$findYear) {
                $query->where('hasAttendance', 1)->where('isFinish', 0)->whereBetween('entryTime', [$findYear['startTime'],$findYear['endTime']]);
                if (isset($data['projectId']) && !empty($data['projectId'])) {
                    $query->where('projectId', $data['projectId']);
                }
                if (isset($data['professionId']) && !empty($data['professionId'])) {
                    $query->where('professionId', $data['professionId']);
                }
                if (isset($data['search']) && !is_null($data['search'])) {
                    $query->where(function ($query1) use ($data) {
                        $query1->where(self::TABLE . '.name', 'like', '%' . $data['search'] . '%')->orWhere('jobNumber', 'like', '%' . $data['search'] . '%');
                    });
                }

            })
            ->orderBy(self::TABLE .'.status', 'asc')
            ->orderBy('p.order', 'desc')
            ->select(self::TABLE . '.*', 'p.name as professionName', 'project.name as projectName');

//        $result = DB::table('attendance')
//            ->leftJoin('employee', 'employee.id', '=', 'attendance.employeeId')
//            ->leftJoin('profession as p', 'p.id', '=', 'employee.professionId')
//            ->leftJoin('project', 'project.id', '=', 'employee.projectId')
//            ->where(function ($query) use ($data,$findYear) {
//                $query->where('hasAttendance', 1)->where('isFinish', 0);
//                if (isset($data['projectId']) && !empty($data['projectId'])) {
//                    $query->where('employee.projectId', $data['projectId']);
//                }
//                if (isset($data['month']) && !empty($data['month'])) {
//                    $query->whereBetween('day',[$data['month'].'-01',date('Y-m-t',strtotime($data['month']))]);
//                }else{
//                    $query->whereBetween('entryTime', [$findYear['startTime'],$findYear['startTime']]);
//                }
//                if (isset($data['professionId']) && !empty($data['professionId'])) {
//                    $query->where('employee.professionId', $data['professionId']);
//                }
//                if (isset($data['search']) && !is_null($data['search'])) {
//                    $query->where(function ($query1) use ($data) {
//                        $query1->where('employee.name', 'like', '%' . $data['search'] . '%')->orWhere('jobNumber', 'like', '%' . $data['search'] . '%');
//                    });
//                }
//
//            })
//            ->orderBy(self::TABLE .'.status', 'asc')
//            ->orderBy('p.order', 'desc')
//            ->groupBy('attendance.employeeId')
//            ->select('employee.*', 'p.name as professionName', 'project.name as projectName');


        if (isset($data['length']) && isset($data['page'])) {
            $limit = config('yucheng.limit');
            $start = 0;
            if (!empty($data['length'])) {
                $limit = $data['length'];
            }
            if (!empty($data['page'])) {
                $start = ($data['page'] - 1) * $limit;
            }
            $result = $result->offset($start)->limit($limit);
        }
        $result = $result->get()->toArray();
        return $result;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function dayValueLists(array $data)
    {
        $lists = $this->attendanceEmployee($data);
        $attendanceModel = new AttendanceModel();

        $findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
        if (empty($findYear)) {
            $findYear['startTime'] = date('Y-01-01 00:00:00');
            $findYear['endTime'] = date('Y-12-31 23:59:59');
        }
        foreach ($lists as $key => $l) {
            $attendance = $attendanceModel->getAttendancesSum($l->id, $findYear['startTime'], $findYear['endTime']);
            $lists[$key]->attendance = $attendance->attendance;
        }

        return $lists;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function countDayValueLists(array $data)
    {
        return $this->countAttendanceEmployee($data);
    }

    /**
     * @param array $data
     * @return mixed
     */
    private function countAttendanceEmployee(array $data)
    {
        $findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
        if (empty($findYear)) {
            $findYear['startTime'] = date('Y-01-01 00:00:00');
            $findYear['endTime'] = date('Y-12-31 23:59:59');
        }
        return DB::table(self::TABLE)
            ->where(function ($query) use ($data,$findYear) {
                $query->where('hasAttendance', 1)->where('isFinish', 0)->whereBetween(self::TABLE.'.entryTime',[$findYear['startTime'],$findYear['endTime']]);
                if (isset($data['projectId']) && !empty($data['projectId'])) {
                    $query->where('projectId', $data['projectId']);
                }
                if (isset($data['professionId']) && !empty($data['professionId'])) {
                    $query->where('professionId', $data['professionId']);
                }
                if (isset($data['search']) && !is_null($data['search'])) {
                    $query->where(function ($query1) use ($data) {
                        $query1->where(self::TABLE . '.name', 'like', '%' . $data['search'] . '%')->orWhere('jobNumber', 'like', '%' . $data['search'] . '%');
                    });
                }
            })
            ->count();
    }

    /**
     * @param $id
     * @return bool
     */
    public function delete($id)
    {
        try{
            $info = (new AttendanceModel())->info(['employeeId'=>$id]);
            if (!empty($info)){
                throw new \Exception("",1);
            }
//            $info = (new LeaveModel())->info(['employeeId'=>$id]);
//            if (!empty($info)){
//                throw new \Exception("",3);
//            }
            $info = (new LivingModel())->info(['employeeId'=>$id]);
            if (!empty($info)){
                throw new \Exception("",4);
            }
            $info = (new LoanModel())->info(['employeeId'=>$id]);
            if (!empty($info)){
                throw new \Exception("",5);
            }
//            $info = (new EmployeeMaterialOrderModel())->info(['employeeId'=>$id]);
//            if (!empty($info)){
//                throw new \Exception("",6);
//            }
//            $info = (new ProjectGroupMembersModel())->info(['employeeId'=>$id]);
//            if (!empty($info)){
//                throw new \Exception("",8);
//            }
            $info = (new WorkmanAccountsModel())->info(['employeeId'=>$id]);
            if (!empty($info)){
                throw new \Exception("",9);
            }
            $info = (new HandymanAccountsModel())->info(['employeeId'=>$id]);
            if (!empty($info)){
                throw new \Exception("",10);
            }
//            $info = (new WarehouseLogModel())->info(['sourceEmployeeId'=>$id]);
//            if (!empty($info)){
//                throw new \Exception("",11);
//            }
            DB::table(self::TABLE)->where(['id'=>$id])->delete();
            return true;
        }catch(\Exception $e){
            $code = $e->getCode();
            switch ($code){
                case 1:
                    $msg = '已记录考勤，不能删除';
                    break;
                case 2:
                    $msg = '已记录考勤，不能删除';
                    break;
                case 3:
                    $msg = '已有请假记录，不能删除';
                    break;
                case 4:
                    $msg = '已有生活费充值记录，不能删除';
                    break;
                case 5:
                    $msg = '已有借款记录，不能删除';
                    break;
                case 6:
                    $msg = '已有材料费记录，不能删除';
                    break;
                case 7:
                    $msg = '已有其他费用记录，不能删除';
                    break;
                case 8:
                    $msg = '已被分配进入班组，不能删除';
                    break;
                case 9:
                    $msg = '已进行人员分账，不能删除';
                    break;
                case 10:
                    $msg = '已进行杂工分账，不能删除';
                    break;
                case 11:
                    $msg = '已存在出入库记录，不能删除';
                    break;
                default:
                    $msg = '不能删除';
            }
            return $msg;
        }
    }

    /**
     * @param $data
     * @return mixed
     */
	public function notInGroup($data){
		$findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
		if (empty($findYear)) {
			$findYear['startTime'] = date('Y-01-01 00:00:00');
			$findYear['endTime'] = date('Y-12-31 23:59:59');
		}
		return DB::table(self::TABLE)
			->where('projectId',$data['projectId'])
			->whereNull('groupId')->whereBetween(self::TABLE.'.entryTime',[$findYear['startTime'],$findYear['endTime']])
			->where('status',1)
			->get()->toArray();
	}

    /**
     * 查找工人中的专业班组人员
     * @param array $ids
     * @return mixed
     */
    public function getTechnicalFromEmployee(array $ids)
    {
        return DB::table(self::TABLE)->whereIn('technicalGroupId',$ids)->pluck('id');
    }
}